﻿using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace CodeContrib.Web.Mvc
{
	// MVCContrib
	public class XmlResult : ActionResult
	{
		private readonly XDocument _document;
		private readonly string _eTag;
		private readonly object _objectToSerialize;

		public object ObjectToSerialize
		{
			get { return _objectToSerialize; }
		}

		public XmlResult(object objectToSerialize, string eTag)
		{
			_eTag = eTag;
			_objectToSerialize = objectToSerialize;
		}

		public XmlResult(XDocument document, string eTag)
		{
			_document = document;
			_eTag = eTag;
		}

		public override void ExecuteResult(ControllerContext context)
		{
			if (_document == null
			    && _objectToSerialize == null)
			{
				return;
			}

			if (_eTag != null)
			{
				context.HttpContext.Response.AddHeader("ETag", _eTag);
			}

			context.HttpContext.Response.Clear();
			context.HttpContext.Response.ContentType = "text/xml";

			if (_document != null)
			{
				using (var writer = XmlWriter.Create(context.HttpContext.Response.OutputStream))
				{
					_document.WriteTo(writer);
					writer.Flush();
				}
			}
			else if (_objectToSerialize != null)
			{
				var serializer = new XmlSerializer(_objectToSerialize.GetType());
				serializer.Serialize(context.HttpContext.Response.Output, _objectToSerialize);
			}
		}
	}
}